package com.huike.framework.aspectj;

import com.huike.common.enums.DaoOperationType;
import com.huike.common.utils.DateUtils;
import com.huike.common.utils.SecurityUtils;
import com.huike.common.annotation.AutoFill;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Objects;

/**
 * @author EthanRuins
 * @date 2023/7/11
 * @apiNote
 */
@Slf4j
@Aspect
@Component
public class AutoFillAspect {
    public static final String SET_CREATE_BY = "setCreateBy";
    public static final String SET_CREATE_TIME = "setCreateTime";
    public static final String SET_UPDATE_BY = "setUpdateBy";
    public static final String SET_UPDATE_TIME = "setUpdateTime";

    /**
     * 切点表达式
     */
    @Pointcut("execution(* com.huike..*Mapper.*(..)) && @annotation(com.huike.common.annotation.AutoFill)")
    public void autoFillPointCut() {
    }

    /**
     * 前置通知，填充新增和更新的公共字段
     * @param joinPoint 切入点
     * @throws Throwable 可能的异常
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws Throwable {
        // 获取到当前被拦截方法的数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature(); // 得到方法签名对象
        AutoFill annotation = signature.getMethod().getDeclaredAnnotation(AutoFill.class); // 获取被拦截方法的注解
        DaoOperationType operationType = annotation.value(); // 获取注解中的数据库操作类型

        // 参数判空
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }

        // 获取拦截方法参数--Entity对象
        Object entity = args[0];

        // 准备赋值的数据
        Date now = DateUtils.getNowDate();
        String username = SecurityUtils.getUsername();

        try {
            Method setUpdateBy = entity.getClass().getSuperclass().getDeclaredMethod(SET_UPDATE_BY, String.class);
            Method setUpdateTime = entity.getClass().getSuperclass().getDeclaredMethod(SET_UPDATE_TIME, Date.class);
            setUpdateBy.invoke(entity, username);
            setUpdateTime.invoke(entity, now);
            if (Objects.equals(operationType, DaoOperationType.INSERT)) {
                Method setCreateBy = entity.getClass().getSuperclass().getDeclaredMethod(SET_CREATE_BY, String.class);
                Method setCreateTime = entity.getClass().getSuperclass().getDeclaredMethod(SET_CREATE_TIME, Date.class);
                setCreateBy.invoke(entity, username);
                setCreateTime.invoke(entity, now);
            }
        } catch (Exception ignored) {
        }
    }
}
